package com.example.wechat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageCompressUtils {
    private static final String TAG = "ImageCompressUtils";
    private static final int MAX_WIDTH = 1280;
    private static final int MAX_HEIGHT = 1280;
    private static final int QUALITY = 80;

    public interface CompressCallback {
        void onSuccess(File compressedFile);
        void onError(String error);
    }

    public static void compressImage(Context context, Uri imageUri, CompressCallback callback) {
        try {
            // 获取图片信息
            InputStream inputStream = context.getContentResolver().openInputStream(imageUri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();

            // 计算压缩比例
            int width = options.outWidth;
            int height = options.outHeight;
            float scale = 1.0f;
            
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                float widthScale = (float) MAX_WIDTH / width;
                float heightScale = (float) MAX_HEIGHT / height;
                scale = Math.min(widthScale, heightScale);
            }

            // 重新读取图片并压缩
            inputStream = context.getContentResolver().openInputStream(imageUri);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();

            if (bitmap == null) {
                callback.onError("无法读取图片");
                return;
            }

            // 调整图片大小
            if (scale < 1.0f) {
                Matrix matrix = new Matrix();
                matrix.postScale(scale, scale);
                Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                bitmap = scaledBitmap;
            }

            // 压缩图片质量
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, baos);
            bitmap.recycle();

            // 保存压缩后的图片
            File outputFile = new File(context.getCacheDir(), "compressed_" + System.currentTimeMillis() + ".jpg");
            FileOutputStream fos = new FileOutputStream(outputFile);
            fos.write(baos.toByteArray());
            fos.close();
            baos.close();

            callback.onSuccess(outputFile);
        } catch (IOException e) {
            Log.e(TAG, "压缩图片失败", e);
            callback.onError("压缩图片失败: " + e.getMessage());
        }
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public static byte[] compressToByteArray(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, stream);
        return stream.toByteArray();
    }
} 